package com.genius.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.genius.auth.bo.LoginBO;
import com.genius.core.JSONResult;
import com.genius.core.LoginUser;
import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import com.genius.service.LoginUserService;
import com.genius.utils.RedisUtils;
import com.genius.utils.SecurityUtils;
import com.genius.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.genius.constant.CodeConstants.LOGIN_CHECK_ID;

@Slf4j
@RestController
@RequestMapping("passport")
@Api(value = "注册登录接口", tags = {"用于注册登录的接口"})
public class PassportController {

    @Autowired
    private LoginUserService loginUserService;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 登陆是否使用图片验证码
     */
    private static final boolean useCheckImage = true;

    @PostMapping("/login")
    @ApiOperation(value = "用户登陆",notes = "用户登陆", httpMethod = "POST")
    public JSONResult login(@Valid @RequestBody LoginBO loginBO) {
        if(useCheckImage){
            checkImageCode(loginBO);
        }
        String username = loginBO.getUsername();
        String password = loginBO.getPassword();
        LoginUser loginUser = loginUserService.login(username,password);
        String token = tokenUtils.createTokenByLoginUser(loginUser);
        return JSONResult.loginSucceed(token);
    }

    @GetMapping("/getCheckImage")
    @ApiOperation(value = "获取图片验证码",notes = "获取图片验证码", httpMethod = "GET")
    public JSONResult getCheckImage() {
        Map<String, Object> result = new HashMap<>();
        result.put("useCheckImage", useCheckImage);
        if(useCheckImage){
            //生成uuid
            String checkId = IdUtil.fastUUID();
            result.put("checkId", checkId);
            //生成验证码
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 45, 5, 10);
            //获取验证码的base64
            result.put("checkImg", lineCaptcha.getImageBase64Data());
            //获取验证码内容
            String checkImageCode = lineCaptcha.getCode();
            redisUtils.setCacheObject(getCheckId(checkId), checkImageCode, 60, TimeUnit.SECONDS);
        }
        return JSONResult.ok(result);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录",notes = "退出登录", httpMethod = "GET")
    public JSONResult logout() {
        try {
            String identityId = SecurityUtils.getLoginUser().getIdentityId();
            tokenUtils.delLoginUserByIdentityId(identityId);
        }catch (Exception e){
            return JSONResult.ok("退出成功");
        }
        return JSONResult.ok("退出成功");
    }

    /**
     * 添加登陆验证码前缀
     * @param uuid 验证码ID
     * @return redis key
     */
    private String getCheckId(String uuid) {
        return LOGIN_CHECK_ID + uuid;
    }

    /**
     * 校验验证码
     * @param loginBO 验证码信息
     */
    private void checkImageCode(LoginBO loginBO){
        //校验验证码
        String checkId = getCheckId(loginBO.getCheckId());
        Boolean hasKey = redisUtils.hasKey(checkId);
        //判断key是否存在，不存在返回失效
        if (hasKey == null || !hasKey) {
            GraceException.display(ResponseType.VERIFICATION_CODE_INVALID_ERROR);
        }
        String checkImageCode = redisUtils.getCacheObject(checkId);
        //验证内容是否匹配
        String checkCode = loginBO.getCheckCode();
        if (!StrUtil.equals(checkImageCode, checkCode)){
            GraceException.display(ResponseType.VERIFICATION_CODE_NOT_MATCH_ERROR);
        }else {
            redisUtils.deleteObject(checkId);
        }
    }

}
